from flask import Blueprint, request, render_template, current_app, flash, redirect, url_for
from flask_login import login_required
from app.models import Role, Auth
from app.constants import ADMIN_PAGE_LIMIT
from app.forms import RoleForm
from app import db


role_controller = Blueprint("role", __name__, url_prefix="/admin/role")

@role_controller.route("/index")
@login_required
def index():
    page = request.args.get('page', 1, type = int)
    keyword = request.args.get('keywords', '', type=str)
    try:
        pagination = Role.query.filter(Role.name.like('%'+keyword+'%')).paginate(page, per_page=ADMIN_PAGE_LIMIT)
    except Exception as e:
        current_app.logger.error(e)

    return render_template("admin/role/index.html", pagination=pagination)

@role_controller.route('/add', methods=["GET", "POST"])
@login_required
def add():
    form = RoleForm()
    if request.method == "POST":
        if form.validate_on_submit():
            name = form.name.data
            auths = request.form.getlist('auths[]')
            if auths:
                try:
                    role = Role(name=name)
                    role.auths = Auth.query.filter(Auth.id.in_(auths)).all()
                    db.session.add(role)
                    db.session.commit()
                except Exception as e:
                    current_app.logger.error(e)
                    flash("添加角色失败")
            else:
                flash("请选择菜单")
            return redirect(url_for('role.index'))
        
    tree = Auth.auth_tree3()
    return render_template("admin/role/add.html", form=form, tree=tree)

@role_controller.route('/edit', methods=["GET", "POST"])
@login_required
def edit():
    id = request.args.get("id", 0, type=int)
    if id == 1:
        flash("超级管理员不能编辑")
        return redirect(url_for('role.index'))

    try:
        role = Role.query.filter_by(id=id).first()
    except Exception as e:
        current_app.logger.error(e)
        flash("角色不存在")
        return redirect(url_for('role.index'))
    
    form = RoleForm(name=role.name)
    if request.method == "POST":
        if form.validate_on_submit():
            name = form.name.data
            auths = request.form.getlist('auths[]')
            if auths:
                try:
                    role.name = name
                    role.auths = Auth.query.filter(Auth.id.in_(auths)).all()
                    db.session.add(role)
                    db.session.commit()
                except Exception as e:
                    current_app.logger.error(e)
                    flash("编辑角色失败")
            else:
                flash("请选择菜单")
            return redirect(url_for('role.index'))
        
    tree = Auth.auth_tree3([a.id for a in role.auths])
    return render_template("admin/role/edit.html", form=form, tree=tree, id=id)

@role_controller.route('/delete_op', methods=["GET"])
@login_required
def delete_op():
    id = request.args.get("id")
    if id:
        id_list = id.split(',')
        try:
            roles = Role.query.filter(Role.id.in_(id_list)).all()
        except Exception as e:
            current_app.logger.error(e)

        has_admin = False
        for role in roles:
            if role.admins:
                has_admin = True
                break
        if not has_admin:
            Role.query.filter(Role.id.in_(id_list)).delete(synchronize_session = False)
        else:
            flash("角色下有管理员，不能删除")
    else:
        flash("请选择要删除的项")
    return redirect(url_for(".index"))
    